<template>
  <div class="container">
    <el-card class="left" >
      <div class="camera-list">
        <el-input v-model="filterCameraText" placeholder="请输入设备名称" :suffix-icon="Search" style="width: 238px; margin: 20px 0;" @input="queryCamera" />

        <el-radio-group v-model="selectedCameraId" class="camera-radio-group" @change="cameraChange">
          <el-tree-v2
            ref="cameraTreeRef"
            v-loading="cameraTreeLoading"
            style="width: 100%; height: 100%;"
            :height="treeHeight"
            :data="cameraTreeData"
            node-key="nodeId" 
            :props="{ value: 'nodeId', label: 'nodeName', children: 'children' }"
            :filter-method="filterCamera"
          >
            <template #default="{ node, data }">
              <template v-if="data.equipmentCameraGroupId">
                <svg-icon icon-class="camera-circle" style="font-size: 18px; position: relative; right: 7px;;" />
                <span style="display: inline-block; width: calc(100% - 90px); height: 26px; line-height: 26px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" >
                  {{ data.nodeName }} 
                </span>
              </template>
              <el-radio v-else :value="data.nodeId" :disabled="data.deviceStatus=='OFFLINE'" > 
                <span v-if="data.deviceStatus=='OFFLINE'" style="color: rgb(200 90 90);">（离线）</span> 
                <span>{{ node.label }}</span>
              </el-radio>
            </template>
          </el-tree-v2>
        </el-radio-group>
      </div>
    </el-card>
    <el-card class="center" >
      <div style="margin-top: 20px; margin-left: 20px; height: 60px">
        <span>选择时间段：</span>
        <el-date-picker
          v-model="queryDate"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          :clearable="false"
          unlink-panels
          :shortcuts="dateTimeShortcuts"
          :disabled-date="disableFutureDate"
        />
        <el-button size="default" type="primary" style="margin-left: 10px" @click="query()">确认</el-button>
      </div>
      <div v-loading="videoLoading" style="position: relative; margin-top: 10px; height: calc(100% - 80px); background-color: #f0f2f5;">
        <p v-if="selectedCamera.equipmentId==null && cameraTreeLoading==false" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
          无可播放设备
        </p>
        <VideoEasyPlayer v-if="selectedCamera.url" :id="selectedCameraId" :url="selectedCamera.url" :is-live="false" @error="videoError" />
      </div>
    </el-card>
    <el-card id="right" class="right" style="min-width: 340px;">
      <div v-loading="cameraInfoLoading || cameraTreeLoading" style="margin-top: 20px; margin-left: 20px; height: 170px;">
        <label style="font-size: 18px">{{ selectedCamera.equipmentName }}</label>
        <el-tooltip placement="top" effect="dark" :content="selectedCamera.equipmentCode" >
          <p style="color: #939292; margin-left: 10px; ">
            <span class="equipment-attr">设备编码</span> <span class="equipment-attr-value">{{ selectedCamera.equipmentCode }}</span>
          </p>
        </el-tooltip>
        <el-tooltip placement="top" effect="dark" :content="getParkPositionStr(selectedCamera.parkBuildingName, selectedCamera.parkBuildingAreaName, selectedCamera.parkBuildingFloorName, selectedCamera.parkBuildingRoomName)" >
          <p style="color: #939292; margin-left: 10px">
            <span class="equipment-attr">设备位置</span> <span class="equipment-attr-value">{{ getParkPositionStr(selectedCamera.parkBuildingName, selectedCamera.parkBuildingAreaName, selectedCamera.parkBuildingFloorName, selectedCamera.parkBuildingRoomName) }}</span>
          </p>
        </el-tooltip>
        <p style="color: #939292; margin-left: 10px">
          <span class="equipment-attr">设备状态</span> <span class="equipment-attr-value">{{ selectedCamera.status == 1 ? '在线' : '离线' }}</span>
        </p>
      </div>
      <div v-loading="videoPlaybackRecordLoading" style="height: calc(100% - 170px); display: flex; flex-direction: column;">
        <label style="font-size: 18px; height: 30px">最近查询记录</label>
        <div style="flex: 1; overflow-y: auto;">
          <template v-for="item in videoPlaybackRecord" :key="item.equipmentId">
            <el-card class="playback-history">
              <div class="playback-history-text">监控名称：{{ item.equipmentName }}</div>
              <div class="playback-history-text">开始时间：{{ parseTime(item.startTime, '{y}-{m}-{d} {h}:{i}') }}</div>
              <div class="playback-history-text">结束时间：{{ parseTime(item.endTime, '{y}-{m}-{d} {h}:{i}') }}</div>
              <el-button style="width: 100px;" size="small" type="primary" @click="playbackHistory(item)">立即查看</el-button>
            </el-card>
          </template>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { parseTime } from '@/utils/linx';
import request from '@/utils/request';
import VideoEasyPlayer from '@/components/VideoEasyPlayer/index.vue';
import { getParkPositionStr } from '@/utils/parkUtil'
import { Search } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const filterCameraText = ref();
const cameraList = ref([]);
const queryDate = ref([
  parseTime(new Date(new Date().getTime() - 2 * 60 * 60 * 1000), '{y}-{m}-{d} {h}:{i}:{s}'),
  parseTime(new Date(new Date().getTime() - 60 * 60 * 1000), '{y}-{m}-{d} {h}:{i}:{s}')
]);

const cameraTreeRef = ref<any>();
const selectedCamera = ref<any>({});
const selectedCameraId = ref();
const videoPlaybackRecord = ref([]);
const videoLoading = ref(false);
const cameraInfoLoading = ref(false);
const videoPlaybackRecordLoading = ref(false);
const treeHeight = ref(0)

const dateTimeShortcuts = [
  {
    text: '今天',
    value: [parseTime(new Date(), '{y}-{m}-{d} 00:00:00'), parseTime(new Date(), '{y}-{m}-{d} 23:59:59')]
  }
]
//  禁止选择未来时间
const disableFutureDate = (time) => {
  return time.getTime() > Date.now();
}

/**
 * 查询摄像头信息列表
 * */
const cameraTreeLoading = ref(false);
const cameraTreeData = ref([]);
const getCameraList = async () => {
  cameraTreeLoading.value = true
  const cameraTreeRes = await request({
    url: '/equipment/equipment-camera-group/tree',
    method: 'get'
  }).finally(() => { cameraTreeLoading.value = false })
  cameraTreeData.value = cameraTreeRes.data;

  console.log('获取摄像机：', cameraTreeData.value);

  //  过滤摄像机列表
  cameraTreeData.value.forEach((item) => {
    if (item.children && item.children.length > 0) {
      cameraList.value = cameraList.value.concat(item.children);
    }
  });

  await nextTick(() => {
    //  展开所有节点
    cameraTreeRef.value?.setExpandedKeys(cameraTreeData.value.map(item=> { return item.nodeId }));

    //  设置默认选中第一个摄像机
    selectedCameraId.value = cameraList.value.filter(item=> item.deviceStatus == 'ONLINE')[0].equipmentId;
    getCameraInfo(selectedCameraId.value);

    // 播放视频
    playVideo(selectedCameraId.value);
  });
};

/**
 * 过滤摄像头
 */
const queryCamera = (query: string) => {
  cameraTreeRef.value!.filter(query)
}

/**
 * 过滤摄像头
 */
const filterCamera = (query: string, data: any) => {
  return data.nodeName!.includes(query)
}

/**
 * 选择摄像头
 */
const cameraChange = async (val) => {
  await getCameraInfo(selectedCameraId.value);

  await playVideo(val);
};

/**
 * 播放视频
 */
const playVideo = async (id) => {
  videoLoading.value = true
  const videoRes = await request({
    url: '/equipment/equipment-info/get-video-url/' + id,
    method: 'get',
    params: { playType: 1, playProtocol: 0, startTime: queryDate.value[0], endTime: queryDate.value[1] }
  }).finally(() => videoLoading.value = false)
  console.log('获取视频地址：', videoRes);

  if (videoRes.data && videoRes.data.media_url) {
    selectedCamera.value.url = JSON.parse(videoRes.data.media_url).wan
    // selectedCamera.value.url = videoRes.data.media_url
  }
};

/**
 * 查看历史记录
 */
const playbackHistory = async (item) => {
  console.log('查看历史记录：', item)

  queryDate.value[0] = item.startTime
  queryDate.value[1] = item.endTime

  selectedCameraId.value = item.equipmentId

  await playVideo(item.equipmentId)
}

/**
 * 获取设备详情
 */
const getCameraInfo = async (id) => {
  cameraInfoLoading.value = true
  const res = await request({ url: '/equipment/equipment-info/' + id, method: 'get' }).finally(() => cameraInfoLoading.value = false)
  console.log('获取设备详情：', res);

  selectedCamera.value = res.data;
};

/**
 * 获取播放记录
 */
const getVideoPlaybackRecord = async () => {
  videoPlaybackRecordLoading.value = true
  const res = await request({ url: '/camera/Video-playback-record/list', method: 'get', params: { pageSize: 10 }}).finally(() => videoPlaybackRecordLoading.value = false)
  console.log('获取播放记录：', res);

  videoPlaybackRecord.value = res.rows
};

/**
 *  查询
 */
const query = async () => {
  if (selectedCameraId.value == null) {
    proxy?.$modal.msgWarning('请选择设备');

    return
  }

  await playVideo(selectedCameraId.value);

  request({
    url: '/camera/Video-playback-record',
    method: 'post',
    data: { equipmentId: selectedCameraId.value, startTime: queryDate.value[0], endTime: queryDate.value[1] }
  }).then((res) => {
    console.log('保存视频查看记录', res)

    getVideoPlaybackRecord()
  });
}

const videoError = (err) => {
  console.error('视频播放失败：', err)
}

onMounted(() => {
  //  设置树高度
  const cameraRadioGroupElement = document.querySelector('.camera-radio-group');
  treeHeight.value = cameraRadioGroupElement.clientHeight

  //  获取播放记录
  getVideoPlaybackRecord()

  //  获取摄像机
  getCameraList();
});
</script>
<style lang="scss" scoped>
.container {
  height: 100%;
  display: flex;
  flex-direction: row !important;
  position: relative;
  background-color: #f4f2f2;
  padding: 6px;
  overflow: hidden;
}
:deep(.el-card__header) {

}
:deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px !important;
}
:deep(.pagination-container) {
  margin-top: 0;
}
:deep(.camera-scene-tabs .el-tabs__nav-scroll) {
  display: flex;
  justify-content: center;
}
:deep(.camera-scene-tabs > .el-tabs__content) {
  padding: 32px;
}
.left {
  height: 100%;
  width: 260px;
  min-width: 260px;
  margin-right: 4px;
}
.center {
  flex: 1;
  height: 100%;
  min-width: 700px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}
.right {
  height: 100%;
  width: 360px;
  min-width: 360px;
  margin-left: 4px;
  background-color: #fff;
  .playback-history {
    margin: 10px;
    :deep(.el-card__body) {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .playback-history-text {
      margin: 10px auto;
      padding: 0;
      font-size: 12px;
    }
  }
  .playback-image {
    width: 100px;
    height: 100px;
    border: 1px solid #8c939d;
  }
}
.camera-list {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.equipment-attr {
  display: inline-block;
  width: 68px;
  overflow: hidden;
}
.equipment-attr-value {
  display: inline-block;
  margin-left: 10px;
  color: #0b0a0a;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: calc(100% - 86px);
}
:deep(.el-tree-node__expand-icon) {
  left: 200px;
  font-size: 14px;
  color: #3c3c3c;
  transform: rotate(180deg);
}
:deep(.el-tree-node__expand-icon.expanded) {
  transform: rotate(90deg);
}
:deep(.camera-radio-group) {
  flex: 1;
  .el-radio-group {
    align-items: flex-start;
  }
}
</style>
